﻿var addcompanyGrid = addcompanyGrid || {};
var isGridLoadFirstime = true;

addcompanyGrid = function () {
    var gridInEditMode = false;
    var addcompanyDropDownChanged = false;
    var addcompanyDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddCompany/GetAddCompany",
                type: "get",
                cache: false,
                dataType: "json",
            },
            create: {
                url: "/AddCompany/CreateAddCompany",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            update: {
                url: "/AddCompany/UpdateAddCompany",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            destroy: {
                url: "/AddCompany/DeleteAddCompany",
                type: "POST",
                dataType: "json",
                contentType: "application/JSON"
            },
            parameterMap: function (options) {
            
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }
        },
        pageSize: 10,
        schema: {
            model: {
                id: "id",
                fields: {
                    id: {
                        editable: false, nullable: true,
                        type: "int"
                    },

                    clientType:
                       {
                           type: "string",
                           validation: { required: true }
                       },
                    companyType:
                        {
                            type: "string"

                        },

                    name: {
                        type: "string",
                        validation: { required: true }
                    },
                    CreatedUser: {

                        type: "string",
                        defaultValue: $('#userLoggedIn').val()
                        // defaultValue:'dan'


                    },
                    website: {
                        type: "string"

                    },
                    phone: {

                        type: "string"
                    },

                    address: {
                        type: "string",
                        //hidden: true,
                        //editable: false,
                        nullable: true,

                    },
                    legalName:
                        {
                            type: "string"
                        },
                    streetOne:
                    {
                        type: "string"
                    },

                    streetTwo:
                  {
                      type: "string"
                  },
                    description: {

                        type: "string"

                    },

                    city: {
                        type: "string"

                    },
                    stateName: {
                        type: "string",
                        validation: { required: true }
                    },

                    zip:
                        {
                            type: "string"
                        },
                    country: {
                        type: "string",
                        defaultValue: "USA"
                    },
                    timeZone:
                        {
                            type: "string",
                            validation: { required: true }
                        },
                    relationStart: {
                        type: "date",
                        editable: false
                    },
                    relationEnd: {
                        type: "date",
                        //  validation: { required: true },
                        nullable: true,
                        value: "",
                        defaultOption: null
                    },
                    stateId: {
                        type: "int",
                        defaultValue: 0
                    },
                    companyTypeId:
                        {
                            type: "int",
                            defaultValue: 0

                        },
                    clientTypeId:
                          {
                              type: "int",
                              defaultValue: 0

                          },

                    error: function (a) {
                        $('#addcompanyGrid').data("kendoGrid").cancelChanges();
                    },
                }
            }
        }
    });

    var states = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddCompany/GetStates/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var companyType = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddCompany/GetCompanyType/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var clientType = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddCompany/GetClientType/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    return {
        addcompanyDataSource: addcompanyDataSource,
        states: states,
        companyType: companyType,
        clientType: clientType,
        gridInEditMode: gridInEditMode


    }

}();

$(function () {

   
    $(window).on("beforeunload", function () {
        if (addcompanyGrid.gridInEditMode) {
            return "Are you sure you want to discard all your changes."
        }

    });
    function dateTimeEditor(container, options) {
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDateTimePicker({});
    }
    $("#addcompanyGrid").kendoGrid({
        dataSource: addcompanyGrid.addcompanyDataSource,
        dataBound: function (e) {
           

            if (isGridLoadFirstime == true) {
                isGridLoadFirstime = false;
                var count = 0; var IsItemFound = false;
                var dataList = e.sender.dataSource.data()
                for (var i = 0; i < dataList.length; i++) {
                    var list = dataList[i];
                    count++;
                    if (list.name == window.location.hash.substr(1)) {
                        IsItemFound = true;
                        break;
                    }
                }

                if (IsItemFound == true) {
                    debugger;
                    var pagesize = e.sender.dataSource.pageSize();
                    debugger;
                    if (pagesize == 10 && count == 10 || count == 20 || count == 30 || count == 40 || count == 50 || count == 60
                        || count == 70 || count == 80 || count == 90 || count == 100 || count == 110 || count == 120 || count == 130 || count == 140 || count == 150 || count == 160 || count == 170 || count == 180 || count == 190 || count == 200
                        || count == 210 || count == 220 || count == 230 || count == 240 || count == 250 || count == 260 || count == 270 || count == 280 || count == 290 || count == 300
                        || count == 310 || count == 320 ) {
                        var currentpage = parseInt(count / pagesize)
                    }
                    else {
                        var currentpage = parseInt(count / pagesize) + 1;
                    }
                        
                    e.sender.dataSource.page(currentpage);
                }

            }

            var rows = e.sender.tbody.children();

            for (var j = 0; j < rows.length; j++) {

                var row = $(rows[j]);
                var dataItem = e.sender.dataItem(row);

                if (dataItem.get("name") == window.location.hash.substr(1)) {
                    debugger;
                    row.addClass("someCssColorClass");
                }
            }
        },
        scrollable: true,
        height: "250px",
        // toolbar: ["create"], //, "save", "cancel"],  
        toolbar: [{ name: "create", text: "Add a new Company" }, "excel"], //, "save", "cancel"],
        excel: {
            allPages: true,
            fileName: "CompanyExport.xlsx"
        },

        pageable: true,
        height: 450,
        columns: [
       { title: "Contacts", filterable: false, width: "8em", template: "<a onclick=\"showContacts('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
        { title: "Projects", filterable: false, width: "6em", template: "<a onclick=\"showProjects('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
          { title: "SalesLead", filterable: false, width: "6em", template: "<a onclick=\"showSalesLead('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
          { title: "MSG", filterable: false, width: "6em", template: "<a onclick=\"showCompanyMessages('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
        { title: "Office", filterable: false, width: "5.5em", template: "<a onclick=\"showCompanyOffices('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },

           { title: "Invoice", filterable: false, width: "8em", template: "<a onclick=\"showInvoice('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
        { title: "History", filterable: false, width: "6em", template: "<a onclick=\"showCompanyHistory('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
        {
            field: "CreatedUser", title: "Created User", filterable: true, width: "10em"
        },
         { field: "name", title: "Name*", filterable: true, width: "8em" },
           { field: "legalName", title: "Registered As", filterable: true, hidden: true, width: "5em" },
             { field: "description", title: "Description", hidden: true, filterable: false, width: "5em" },
               { field: "phone", title: "Phone", width: "9em" },
                { field: "fax", title: "Fax", width: "9em", hidden: true },
                   { field: "clientType", title: "ClientType*", width: "10em", editor: clientTypeDropDownEditor, },
                { field: "companyType", title: "CompanyType", width: "10em", editor: companyTypeDropDownEditor },
            { field: "website", title: "WebSite", width: "10em" },
               { field: "streetOne", title: "Street One", hidden: true },
           { field: "streetTwo", title: "Street two", hideen: true },
           { field: "city", title: "City", width: "7em" },
                { field: "stateName", title: "State*", editor: stateDropDownEditor, width: "8em" },
                 { field: "country", title: "Country", hidden: true, editor: countryDropDownEditor, width: "8em" },

           { field: "address", readonly: true, title: "Address", width: "10em" },
             //{ field: "address", title: "Address", width: "10em", editor: autoComplete },

                  { field: "zip", title: "ZipCode", width: "8em" },
                   { field: "timeZone", title: "Time Zone*", width: "9em", editor: timeZoneDropDownEditor },
                     {
                         field: "relationStart", title: "Relation StartDate", format: "{0:MM/dd/yyyy}", width: "12em", template: "#= kendo.toString(kendo.parseDate(relationStart, 'yyyy-MM-dd'), 'MM/dd/yyyy') #",

                     },

                      {
                          field: "relationEnd", title: "Relation EndDate", hidden: true, filterable: false, format: "{0:MM/dd/yyyy}",
                          editor: dateTimeEditor,
                          filterable: {
                              ui: "datetimepicker"
                          }


                      },
                         {
                             field: "notes", title: "Notes",
                             width: "200px",
                             attributes: {
                                 style: 'white-space: nowrap '
                             },
                             sortable: true,


                             editor: function (container, options) {
                                 $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                             }
                         },


      {
          title: "&nbsp;",
          width: "15em",

          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {

                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later


                      deleteTopicConfirmation(e, this);

                      return false;
                  }
              }
          ]
      }
        ],

        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                    contains: "Contains",
                }
            }
        },
        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },

        selectable: "multiple, row",
        edit: function (e) {
            e.container.find(".k-edit-label:nth-child(1)").hide();
            e.container.find(".k-edit-field:nth-child(1)").hide();

            e.container.find(".k-edit-label:nth-child(2)").hide();
            e.container.find(".k-edit-field:nth-child(2)").hide();
            e.container.find(".k-edit-label:nth-child(3)").hide();
            e.container.find(".k-edit-field:nth-child(3)").hide();
            e.container.find(".k-edit-label:nth-child(4)").hide();
            e.container.find(".k-edit-field:nth-child(4)").hide();
            e.container.find(".k-edit-label:nth-child(5)").hide();
            e.container.find(".k-edit-field:nth-child(5)").hide();
            e.container.find(".k-edit-label:nth-child(6)").hide();
            e.container.find(".k-edit-field:nth-child(6)").hide();
            e.container.find(".k-edit-label:nth-child(7)").hide();
            e.container.find(".k-edit-field:nth-child(7)").hide();
            e.container.find(".k-edit-label:nth-child(8)").hide();
            e.container.find(".k-edit-field:nth-child(8)").hide();


            e.container.find(".k-edit-label:nth-child(9)").hide();
            e.container.find(".k-edit-field:nth-child(10)").hide();
            e.container.find(".k-edit-label:nth-child(11)").hide();
            e.container.find(".k-edit-field:nth-child(12)").hide();

            e.container.find(".k-edit-label:nth-child(13)").hide();
            e.container.find(".k-edit-field:nth-child(13)").hide();
            e.container.find(".k-edit-label:nth-child(14)").hide();
            e.container.find(".k-edit-field:nth-child(14)").hide();


            //e.container.find(".k-edit-label:nth-child(37)").hide();
            //e.container.find(".k-edit-field:nth-child(38)").hide();
            e.container.find(".k-edit-label:nth-child(43)").hide();
            e.container.find(".k-edit-field:nth-child(44)").hide();




            addcompanyGrid.gridInEditMode = true;
        },
        cancel: function () {
            addcompanyGrid.gridInEditMode = false;
        },
        excelExport: function (e) {
            for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                e.workbook.sheets[0].columns[i].autoWidth = true;
            }
        }
    })

    $("#addcompanyGrid").kendoTooltip({
        filter: "td:nth-child(27)", //this filter selects the second column's cells
        position: "right",
        content: function (e) {
            var target = e.target;
            return $(target).text();

        }
    }).data("kendoTooltip");
    $("#dirty").on("click", function (e) {
        $.ajax({
            url: "/AddCompany/GetCompanyByLoggedInUser",
            type: "get",
            cache: false,
            dataType: "json",
            success: function (data) {
                var grid = $('#addcompanyGrid').getKendoGrid();
                $("#addcompanyGrid").data("kendoGrid").dataSource.data(data);
            }
        });
        return false;

    });
    $("#all").on("click", function (e) {
        $.ajax({
            url: "/AddCompany/GetAddCompany",
            type: "get",
            cache: false,
            dataType: "json",
            success: function (data) {
                var grid = $('#addcompanyGrid').getKendoGrid();
                $("#addcompanyGrid").data("kendoGrid").dataSource.data(data);
            }
        });
    });




    addcompanyGrid.addcompanyDataSource.bind("requestEnd", showSuccessMessage);
    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            addcompanyGrid.gridInEditMode = false;
            $("#saveConfirm").addClass('in');
            e.sender.read();

            var grid = $('#addcompanyGrid').data("kendoGrid");
            var dataSource = grid.dataSource;
            var total = dataSource.data().length;
            dataSource.insert(total, {});
            dataSource.page(dataSource.totalPages());
            grid.editRow(grid.tbody.children().last());
            var row = grid.tbody.children().last();
        }
    }

    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });

    function textareaEditor(container, options) {
        $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="5"></textarea>')
            .appendTo(container);
    }

    function deleteTopicConfirmation(e, widget) {
        var grid = $('#addcompanyGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }

    function stateDropDownEditor(container, options) {
        $('<input required="required" name="State" data-text-field="stateName" data-value-field="id" data-bind="value:stateId"/>').appendTo(container).kendoDropDownList({
            autoBind: true,
            placeholder: "Select State",
            dataSource: addcompanyGrid.states
        });
        $('<span class="k-invalid-msg" data-for="State"></span>').appendTo(container);
    }
    function countryDropDownEditor(container, options) {
        $('<input data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: { data: [{ dataText: "USA", dataValue: "1" }, { dataText: "CANADA", dataValue: "2" }, { dataText: "FRANCE", dataValue: "3" }, { dataText: "ITALY", dataValue: "4" }, { dataText: "ENGLAND", dataValue: "5" }] }
        });
    }


    function timeZoneDropDownEditor(container, options) {
        $('<input required="required" name = "TimeZone" id="timeZoneId" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            placeholder: "Select TimeZone",
            dataSource: { data: [{ dataText: "ET", dataValue: "1" }, { dataText: "CT", dataValue: "2" }, { dataText: "PT", dataValue: "3" }, { dataText: "MT", dataValue: "4" }] }
        }); $('<span class="k-invalid-msg" data-for="TimeZone"></span>').appendTo(container);
    }

    function companyTypeDropDownEditor(container, options) {

        $('<input data-text-field="companyType" data-value-field="id"  data-bind="value:companyTypeId"/>').appendTo(container).kendoDropDownList({
            autoBind: true,
            optionLabel: "select a company type",
            dataSource: addcompanyGrid.companyType

        });
    }

    function clientTypeDropDownEditor(container, options) {
        $('<input required="required" name="ClientType"  data-text-field="clientType" data-value-field="id" data-bind="value:clientTypeId"/>').appendTo(container).kendoDropDownList({

            autoBind: true,
            optionLabel: "select a client type",

            dataSource: addcompanyGrid.clientType
        });
        //$('<span class="k-invalid-msg" data-for="ClientType"></span>').appendTo(container);
    }
});


